﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Nomo.FiniteStateMachineModule
{
    /// <summary>
    /// 有限状态机。
    /// </summary>
    public sealed class FiniteStateMachine
    {
        private readonly List<IState> _states = new List<IState>(8);

        private IState _defaultState;

        /// <summary>
        /// 默认状态。
        /// </summary>
        public IState DefaultState
        {
            get => GetDefaultState();
            set
            {
                if (_states.Contains(value))
                {
                    _defaultState = value;
                }

                throw new InvalidOperationException();
            }
        }

        private IState GetDefaultState()
        {
            return _defaultState ?? (_defaultState = _states.FirstOrDefault());
        }

        /// <summary>
        /// 当前状态。
        /// </summary>
        public IState Current { get; private set; }

        /// <summary>
        /// 向有限状态机添加一个状态。
        /// </summary>
        /// <param name="state"></param>
        public void AddState(IState state)
        {
            if (state == null)
            {
                return;
            }

            if (_states.Any(e => e.ID == state.ID))
            {
                return;
            }

            _states.Add(state);
        }

        /// <summary>
        /// 从有限状态机里移除一个状态。
        /// </summary>
        /// <param name="id">状态的 ID .</param>
        public void RemoveState(int id)
        {
            _states.RemoveAll(s => s.ID == id);
        }

        /// <summary>
        /// 更新。
        /// </summary>
        public void Update()
        {
            if (Current == null)
            {
                Current = GetDefaultState();
                if (Current == null)
                {
                    return;
                }
                Current.OnEnter();
            }

            if (Current.Switch(out var id))
            {
                Current.OnExit();
                Current = _states.First(state => state.ID == id);
                Current.OnEnter();
            }

            Current.OnUpdate();
        }
    }
}
